package org.ipccenter.balancechecker.jaxb;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlAdapter;

import org.ipccenter.balancechecker.listener.Listener;
import org.ipccenter.balancechecker.services.MiptTelecom;
import org.ipccenter.balancechecker.services.Service1;
import org.ipccenter.balancechecker.services.ServiceType;

public class ServiceTypeAdapter extends
        XmlAdapter<ServiceTypeAdapter.AdaptedServiceType, ServiceType> {
    @Override
    public AdaptedServiceType marshal(ServiceType service) throws Exception {
        if (null == service) {
            return null;
        }
        AdaptedServiceType adaptedServiceType  = new AdaptedServiceType();
        if (service instanceof MiptTelecom) {
            MiptTelecom mipt = (MiptTelecom) service;
            adaptedServiceType.name = mipt.getName();
            adaptedServiceType.username = mipt.getUsername();
            adaptedServiceType.password = mipt.getPassword();
        }
        if(service instanceof Service1) {
            MiptTelecom service1 = (MiptTelecom) service;
            adaptedServiceType.name = service1.getName();
            adaptedServiceType.username = service1.getUsername();
            adaptedServiceType.password = service1.getPassword();
        }
        return adaptedServiceType;
    }

    @Override
    public ServiceType unmarshal(AdaptedServiceType adaptedServiceType) {
        if (null == adaptedServiceType) {
            return null;
        }
        if ("MIPT-Telecom".equals(adaptedServiceType.name)) {
            MiptTelecom mipt = new MiptTelecom();
            mipt.setName("Mipt-Telecom");
            mipt.setPassword(adaptedServiceType.password);
            mipt.setUsername(adaptedServiceType.username);
            mipt.setListener(adaptedServiceType.listener);
            return mipt;
        }
        if("Service1".equals(adaptedServiceType.name)) {
            Service1 service1 = new Service1();
            service1.setName("Service1");
            service1.setPassword(adaptedServiceType.password);
            service1.setUsername(adaptedServiceType.username);
            service1.setListener(adaptedServiceType.listener);
            return service1;
        }
        return null;
    }
    @XmlRootElement(name = "service")
    @XmlAccessorType(XmlAccessType.FIELD)
    public static class AdaptedServiceType {

        @XmlAttribute
        public String name;

        @XmlElement
        public String username;

        @XmlElement
        public String password;

        @XmlElement(name="listener")
        Listener listener;

    }

}

